package com.luckberry.murder.controller.api;

import com.alibaba.fastjson.JSON;
import com.luckberry.murder.entity.User;
import com.luckberry.murder.entity.VIP;
import com.luckberry.murder.service.UserService;
import com.luckberry.murder.service.VIPService;
import com.luckberry.murder.util.JSONUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api")
public class ApiVIPController {

    @Resource
    private VIPService service;
    @Resource
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/vips", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getVIPs() {
        return JSON.toJSONString(service.getVIPs());
    }

    @ResponseBody
    @RequestMapping(value = "/vip/{uid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getVIP(@PathVariable("uid") int uid) {
        return JSON.toJSONString(service.getVIP(uid));
    }

    @ResponseBody
    @RequestMapping(value = "/vip", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public String addVIP(HttpSession session, @RequestBody String json) {
        VIP vip = JSON.parseObject(json, VIP.class);

        // 续费
        VIP oldVip = service.getVIP(vip.getUid());
        if (oldVip != null) {
            vip.setMonth(vip.getMonth() + oldVip.getMonth());
            return JSONUtil.result(service.editVIP(vip));
        }

        // 购买VIP
        boolean result = service.addVIP(vip);
        if (result) {
            User user = userService.getUser(vip.getUid());
            user.setPerm("vip");
            userService.editUser(user);
            session.setAttribute("user", userService.getUser(vip.getUid()));
        }
        return JSONUtil.result(result);
    }

    @ResponseBody
    @RequestMapping(value = "/vip/{uid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.DELETE)
    public String deleteVIP(HttpSession session, @PathVariable("uid") int uid) {
        boolean result = service.deleteVIP(uid);
        if (result) {
            User user = userService.getUser(uid);
            user.setPerm("user");
            userService.editUser(user);
            session.setAttribute("user", userService.getUser(uid));
        }
        return JSONUtil.result(result);
    }

    @ResponseBody
    @RequestMapping(value = "/vip", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.PUT)
    public String editVIP(@RequestBody String json) {
        return JSONUtil.result(service.editVIP(JSON.parseObject(json, VIP.class)));
    }
}
